<template>
  <div>
    <!-- 头部 放置支付流程 -->
    <el-header class="order-head flex">
      <span><img src="../assets/logo.png" height="100px"></span>
      <div>
        <el-steps :active="1" align-center style="margin-left:500px">
          <el-step title="乘机信息" description="填写乘客信息，最多3人"></el-step>
          <el-step title="支付" description="跳转支付"></el-step>
          <el-step title="完成" description="购买机票完毕"></el-step>
        </el-steps>
      </div>
    </el-header>
    <!-- 主体 -->
    <el-main class="order-main j-s flex">
      <!-- 左侧订单乘客信息表单 -->
      <div class="main-content">
        <el-form :model="this.formData" class="ticket-form">
          <div class="flex form-item" :key="index" v-for="(item,index) in formData.Customer">
            <div class="form-content">
              <el-form-item label="姓名" label-width="100px">
                <el-input v-model="item.name" placeholder="姓名,与证件姓名一致"></el-input>
              </el-form-item>
              <el-form-item label="身份证" label-width="100px">
                <el-input type="number" v-model="item.id" placeholder="证件号"></el-input>
              </el-form-item>
              <el-form-item label="联系方式" label-width="100px">
                <el-input type="number" v-model="item.phone" placeholder="11位手机号"></el-input>
              </el-form-item>
            </div>
            <div class="form-logo">
              <img src="../assets/ticket-logo.jpg" width="100px">
            </div>
            <div style="margin-right : 10px">
              <el-button type="warning" size="mini" @click="removeCustomer(index)" icon="el-icon-remove-outline">删除乘客</el-button>
            </div>
          </div>
        </el-form>
        <el-button id="btn-add" @click="addCustomer" icon="el-icon-circle-plus-outline">新增乘客</el-button>
      </div>
      <!-- 右侧航班信息卡片 -->
      <div class="main-card">
        <el-card shadow="hover">
          <div slot="header">
            <span>航班信息</span>
          </div>
          <plane-detail v-bind:routeInfo="this.routeInfo"></plane-detail>
          <div id="total-price"></div>
        </el-card>
      </div>
    </el-main>
    <!-- 底部确认按钮 -->
    <el-button icon="el-icon-check" type="primary" class="bottom-btn" @click="submitOrder" :disabled="inQuering" :loading="inQuering">下 一 步
    </el-button>
    <el-button icon="el-icon-close" type="warning" class="bottom-btn" @click="cancelOrder">取 消</el-button>
  </div>
</template>

<script>
import axios from "axios";
import CheckSeat from "../components/CheckSeat.vue";
import FlightEditor from "../components/FlightEditor.vue";
import PlaneDetail from "../components/PlaneDetail.vue";

export default {
  components: { PlaneDetail, FlightEditor, CheckSeat },
  name: "Order",
  data() {
    return {
      inQuering: false,
      routeInfo: {},
      formData: {
        Customer: [
          {
            phone: "",
            name: "",
            id: ""
          }
        ]
      }
    };
  },
  methods: {
    cancelOrder() {
      this.$router.replace("/");
    },
    addCustomer() {
      // 添加乘客 最大人数不超过3
      if (this.formData.Customer.length < 4) {
        this.formData.Customer.push({ phone: "", name: "", id: "" });
      } else {
        this.$message.warning("用户人数达到上限");
      }
    },
    removeCustomer(index) {
      // 删除乘客
      if (this.formData.Customer.length > 1)
        this.formData.Customer.splice(index, 1);
    },
    checkPhone(phones) {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(phones)) {
        return false;
      } else {
        return true;
      }
    },
    checkID(cid) {
      // var arrExp = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
      // var arrValid = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2]; //校验码
      // if (/^\d{17}\d|x$/i.test(cid)) {
      //   var sum = 0,
      //     idx;
      //   for (var i = 0; i < cid.length - 1; i++) {
      //     // 对前17位数字与权值乘积求和
      //     sum += parseInt(cid.substr(i, 1), 10) * arrExp[i];
      //   } // 计算模（固定算法）
      //   idx = sum % 11; // 检验第18为是否与校验码相等
      //   return arrValid[idx] == cid.substr(17, 1).toUpperCase();
      // } else {
      //   return false;
      // }
      return true;
    },
    submitOrder() {
      // 上传订单
      // 对每张机票、每个人上传一次
      // 正确顺序应该是先查询余票，减少余票再生成机票，此处直接逐个生成机票不妥
      this.inQuering = true;
      var ok = true;
      for (let person of this.formData.Customer) {
        if (person.phone === "" || person.name === "" || person.id === "") {
          this.$message({
            message: "请先填写全部信息",
            type: "warning"
          });
          ok = false;
        }
        if (this.checkID(person.id) == false) {
          this.$message({
            message: person.name + "身份证填写错误",
            type: "warning"
          });
          ok = false;
        }
        if (this.checkPhone(person.phone) == false) {
          this.$message({
            message: person.name + "电话号码填写错误",
            type: "warning"
          });
          ok = false;
        }
      }
      if (ok == false) {
        this.inQuering = false;
        return;
      }
      for (let flight of this.routeInfo.flights) {
        for (let person of this.formData.Customer) {
          console.log(flight);
          axios
            .post(this.$GLOBAL.localHost + "bookticket/", {
              startTime: flight.startTime,
              flightName: flight.flightName,
              terminal: "12A",
              flightId: flight.flightId,
              price: flight.price,
              passengerId: person.id,
              passengerName: person.name,
              userId: this.$GLOBAL.username
            })
            .then(response => {
              this.inQuering = false;
              console.log(response.data);
              if (response.data.success == 1) {
                this.$message.success("购票成功");
                this.$router.replace("/");
              } else {
                if (response.data.success == 0) {
                  this.$message.error("您的信用等级过低");
                }
                if (response.data.success == -1) {
                  this.$message.error("余票不足");
                }
                this.$router.replace("/");
              }
            })
            .catch(error => {
              console.log(error);
              this.$message.error("服务器异常");
              this.inQuering = false;
            });
        }
      }
    }
  },
  computed: {},
  created() {
    let info = decodeURIComponent(this.$route.params.info);
    this.routeInfo = JSON.parse(info);
  },
  mounted() {
    this.$notify({
      title: "注意",
      message: "请仔细填写乘客信息，您最多可为3名不同乘客购买机票",
      duration: 0
    });
    this.$notify({
      title: "警告",
      message: "如果您在本月内退票超过3次，本次购票将不会成功",
      type: "warning",
      duration: 0
    });
  }
};
</script>

<style scoped>
.order-head {
  width: 1200px;
  height: 200px;
  padding-left: 100px;
  position: relative;
}
.flex {
  display: flex;
}
.j-c {
  justify-content: center;
}
.j-s {
  justify-content: space-between;
}
.a-c {
  align-content: center;
}
.order-main {
  background: #eaf0f3;
  margin-top: 75px;
  width: 100%;
  height: 100%;
}
.main-content {
  min-width: 700px;
  min-height: 500px;
  background: white;
}
.main-card {
  position: sticky;
  top: 0;
  min-width: 400px;
}
.ticket-form {
  padding: 10px 5px;
  border-right: 2px solid #dcdfe6;
  border-left: 2px solid #dcdfe6;
}
.form-logo {
  width: 200px;
  margin: 50px 0;
}
.form-content {
  padding: 20px 10px 0 0;
  border-right: 1px #c4cad5 dashed;
  min-width: 400px;
}
.form-item {
  border: 2px solid #e4e7ed;
  margin: 5px;
  padding: 10px 0;
}
.bottom-btn {
  width: 300px;
  margin: 20px;
}
#btn-add {
  float: right;
  margin: 10px 10px;
}
.test {
  padding: 10px;
  margin: 20px;
  border: 2px solid red;
}
</style>